//
//  BN_DynamicClassData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-29.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_DynamicClassData.h"
#import "AppDelegate.h"

@implementation BN_DynamicClassData {
    NSIndexPath *currentIndexPath;
    BN_ClassParentCell *currentCell;
    NSArray *files_;
    NSInteger replTime_;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
}

- (void)loadNetData {
    
    // 关闭当前播放的视频
    [[NSNotificationCenter defaultCenter]postNotificationName:@"K_ANYTIME_REMOVE_MOVIE" object:nil];
    
    __weak typeof(self) weakSelf = self;
    _dynamicHelper.queryClassListCompleteHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            [LZCHINT title:errorMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            weakSelf.listReload(YES,weakSelf.isScrollToTop);
        }
        if(result){
            [weakSelf useNetDate:result];
        }
    };
    // 测试加载第一页
    [_dynamicHelper refreshClassList];
    
}

// 得到下一页数据
- (void)loadNextNetData {
    __weak typeof(self) weakSelf = self;
    _dynamicHelper.queryClassListCompleteHandler = ^(id result,NSString *errorMsg){
        
        if (errorMsg) {
            [LZCHINT title:errorMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
        }
        // update by jason yan 2014-05-30
        if(result){
            [weakSelf useNetDate:result];
        }
    };
    // 测试加载第二页班级动态
    [_dynamicHelper fetchNextPageForClass];
}

// 获得数据 重新加载Tableview
- (void)useNetDate:(id)info {
    self.netArray = (NSMutableArray *)info;
    [self.classTableView reloadData];
    self.listReload(YES,self.isScrollToTop);
}

- (void)toDynamic_NoticeReloadList:(Dynamic_Notice_ReloadList)reloadList {
    self.listReload = reloadList;
}

- (id)init {
    if (self = [super init]) {
        // UI
        self.classTableView = [[UITableView alloc]init];
        if (IOS7) {
            self.classTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.classTableView.contentInset = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
            self.classTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
        }else {
            self.classTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-CLASSPARENTVIEWHEIGHT);
            self.classTableView.contentInset = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
            self.classTableView.scrollIndicatorInsets = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
        }
        self.classTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.classTableView.delegate = self;
        self.classTableView.dataSource = self;
        [self setExtraCellLineHidden:self.classTableView];
        
        // 下拉刷新
        MJRefreshHeaderView *header = [MJRefreshHeaderView header];
        header.scrollView = self.classTableView;
        header.delegate = self;
        _header = header;
        
        // 上拉加载更多
        MJRefreshFooterView *footer = [MJRefreshFooterView footer];
        footer.scrollView = self.classTableView;
        footer.delegate = self;
        _footer = footer;
        
        // 初始化动态Helper
        if (!_dynamicHelper) {
            _dynamicHelper = [[BN_DynamicHelper alloc]init];
        }
        [self loadNetData];
        
        NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
        [userD setInteger:0 forKey:USERDEFAULTS_CLASSPARENT];
        [userD synchronize];
        
        if ([self.classTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.classTableView setSeparatorInset:UIEdgeInsetsZero];
        }
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeVideoView:) name:@"KREMOVE_VIDEOPLAYER" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(likeChangeNetArr:) name:K_CLASS_LIKE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareChangeNetArr:) name:K_CLASS_SHARE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleChangeNetArr:) name:K_CLASS_DELETE_NETARRAY_VALUE object:nil];

    }
    return self;
}

#pragma mark
#pragma mark 刷新
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];

    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (_header == refreshView) {
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.0];
    }else {
        [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0.0];
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // code...
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark
#pragma mark UIScrollViewDelegae

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
}

float currentContentOffset;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    currentContentOffset = scrollView.contentOffset.y;
    
    // 微视视频效果
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    UIWindow *window = appDelegate.window;
    BN_ClassParentCell *cell = (BN_ClassParentCell *)[self.classTableView cellForRowAtIndexPath:currentIndexPath];
    for (cell in self.classTableView.visibleCells) {
        CGRect f = [self.classTableView convertRect:cell.frame toView:window];
        if (CGRectIntersectsRect(f, self.lineLabel.frame)) {
            currentCell = cell;
        }else{
            if (cell.moviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
                [cell removeMovieView];
            }
        }
    }

    // 切换的View隐藏时-慢慢向下拉-拉到最底部时-切换的View显示
    if (currentContentOffset == -99) {
        [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 此处判断2G/3G、WiFi、网络连接失败
    if ( [IMB_NetUtils checkGPRSNet]) {
        NSLog(@"GPRS");
    }else if([IMB_NetUtils checkWifiNet]){
        NSLog(@"WiFi");
        if ([currentCell.fileFlg isEqualToString:@"1"]) {
            [currentCell playVideoAction:nil];
        }
    }else {
        NSLog(@"无网络连接");
    }
}

// 判断向上或向下滚动
float lastContentOffset;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    if (currentContentOffset > 0) {
        if (lastContentOffset < scrollView.contentOffset.y) {
            // NSLog(@"向上滚动显示");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"hide"];
            
        }else{
            // NSLog(@"向下滚动隐藏");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
        }
    }
}

#pragma mark 列表的委托与dataSource

- (void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    view.backgroundColor = [UIColor orangeColor];
    [tableView setTableFooterView:view];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BN_ClassParentCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 配置cell
    static NSString *identifier = @"BN_ClassParentCell";
    BOOL nibsResistered = NO;
    if (!nibsResistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_ClassParentCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        nibsResistered = YES;
    }
    BN_ClassParentCell *cell = (BN_ClassParentCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    cell.tag = indexPath.row;
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    for (UIView *view in cell.disPlayImageView.subviews) {
        [view removeFromSuperview];
    }
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    cell.cellHeight = 0;
    cell.relpHeight = 0;
    cell.singleRelpHeight = 0;

    
     // 用户权限
    NSInteger postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    NSLog(@"%ld",(long)postUserType);
    
    cell.postUserId = [self.netArray[indexPath.row][@"postUserId"] integerValue];
    cell.postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    
    // 用户名称
    cell.userNameLabel.text = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postUserName"]];
    
    // 用户头像
    NSString * postHeadUrlStr = self.netArray[indexPath.row][@"postHeadUrl"];
    if (![postHeadUrlStr isEqual:[NSNull null]]) {
        postHeadUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:postHeadUrlStr];
        NSURL *postHeadUrl = [NSURL URLWithString:postHeadUrlStr];
        [cell.userPhotoImageView setImageWithURL:postHeadUrl placeholderImage:[UIImage imageNamed:@"userPhoto"]];
        cell.userPhotoImageView.layer.masksToBounds = YES;
        cell.userPhotoImageView.layer.cornerRadius = 18;
    }else {
        cell.userPhotoImageView.image = [UIImage imageNamed:@"userPhoto"];
    }
    
    // 发布时间
    NSString *dateStr = self.netArray[indexPath.row][@"postDate"];
    NSRange rang = NSMakeRange(0, 19);
    NSString *strRang = [dateStr substringWithRange:rang];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateTime = [formatter dateFromString:strRang];
    cell.createTimeLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
    
    // 浏览次数 browTime
    NSString *browTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"browTime"]];
    if (![browTime isEqual:[NSNull null]]) {
        cell.browseTimeLabel.text = [NSString stringWithFormat:@"浏览%@次",browTime];
    }else {
        cell.browseTimeLabel.text = @"浏览0次";
    }
    
    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    // 喜欢标记
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];
    // 喜欢数
    cell.praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    // postId
    cell.postId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postId"]];
    // 评论数
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
    
    
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    
    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pinglunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {

            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                break;
        }
        pinlunLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pinglunBtn addSubview:pinlunLabel];
    }
    
    if (![praiTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.xihuanBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *xihuanLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {
            case 6:
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                break;
        }
        xihuanLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        xihuanLabel.textColor = color;
        xihuanLabel.font = [UIFont systemFontOfSize:12];
        xihuanLabel.text = praiTime;
        [cell.xihuanBtn addSubview:xihuanLabel];
    }
    [cell dealLikeBtnColorState];
    
    
    // 评论数组
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
    
    // 文字内容
    NSString *postSubj = self.netArray[indexPath.row][@"postSubj"];
    if (![postSubj isEqual:[NSNull null]]) {
        cell.contentTextLabel.text = postSubj;
    }
    
    // UI
    NSString *fileFlg = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    cell.fileFlg = fileFlg;
    NSArray *files = self.netArray[indexPath.row][@"files"];
    if ([fileFlg isEqualToString:@"0"]) {
        [cell groupImageView:files];
    }else {
        [cell groupVideo:files];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark
#pragma mark Notification Action

- (void)classRefresh {
    if (!self.dynamicHelper) {
        self.dynamicHelper = [[BN_DynamicHelper alloc]init];
    }
    [self loadNetData];
}

- (void)removeVideoView:(NSNotification *)notification {
    [currentCell removeMovieView];
}

// 数据源改变
- (void)likeChangeNetArr:(NSNotification *)notification {
    // praiFlg
    NSArray *recevieArr = notification.object;
    NSInteger tag = [recevieArr[0] integerValue];
    NSInteger praiFlg = [recevieArr[1] integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    // 点赞标记
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiFlg] forKey:@"praiFlg"];
    // 点赞次数
    NSInteger praiTime = [dict[@"praiTime"]integerValue];
    switch (praiFlg) {
        case 0:
            praiTime = praiTime - 1;
            break;
        case 1:
            praiTime = praiTime + 1;
            break;
        default:
            break;
    }
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiTime] forKey:@"praiTime"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    [self.classTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
}

- (void)shareChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    [dict setObject:@"1" forKey:@"favoFlg"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    [self.classTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
}

- (void)deleChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object intValue];
    [self.netArray removeObjectAtIndex:tag];
    [self.classTableView reloadData];
}

#pragma mark dealloc
- (void)dealloc
{
    NSLog(@"动态_班级 Modal 释放");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDISPLAYHIDEDYNAMICUIVIEW object:nil];    
    [_header free];
    [_footer free];
}

@end
